package com.hch.datastructure.lru;

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

/**
 * @author HeCongHui
 * @date 2022/6/23 19:22
 */
public class LruCacheLinkedMap {
    int cap;

    Map<Integer, Integer> cache = new LinkedHashMap<>();

    private void makeRecently(int key) {
        Integer integer = cache.get(key);
        cache.remove(integer);
        cache.put(key, integer);
    }

    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        }
        return cache.get(key);
    }

    public void put(int key, int val) {

        if (cache.containsKey(key)) {
//            修改key的值
            cache.put(key, val);
            makeRecently(key);
            return;
        }
        if (cache.size() >= this.cap) {
//            链表第一个值就是最少使用的
            Integer first = this.cache.keySet().iterator().next();
            this.cache.remove(first);

        }
        cache.put(key, val);

    }

}
